package cn.sciento.starter.tenant.custom.core;

import javax.servlet.http.HttpServletRequest;
import cn.sciento.starter.tenant.custom.repository.TenantCustomPointRepository;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.servlet.mvc.condition.RequestCondition;

public class TenantCustomRequestCondition implements RequestCondition<TenantCustomRequestCondition> {
  private static final Logger LOGGER = LoggerFactory.getLogger(TenantCustomRequestCondition.class);
  
  private final String customPointCode;
  
  private final TenantCustomPointRepository tenantCustomPointRepository;
  
  private final String serviceName;
  
  public TenantCustomRequestCondition combine(TenantCustomRequestCondition other) {
    return this;
  }
  
  public TenantCustomRequestCondition(String customPointCode, String serviceName, TenantCustomPointRepository tenantCustomPointRepository) {
    this.customPointCode = customPointCode;
    this.serviceName = serviceName;
    this.tenantCustomPointRepository = tenantCustomPointRepository;
  }
  
  public TenantCustomRequestCondition getMatchingCondition(HttpServletRequest request) {
    if (this.tenantCustomPointRepository.getPriority(TenantCustomContext.getTenantNum(), this.serviceName, this.customPointCode) != null) {
      LOGGER.debug("Tenant had authority to custom handler: tenantNum={}, customPointCode={}", TenantCustomContext.getTenantNum(), this.customPointCode);
      return this;
    } 
    return null;
  }
  
  public int compareTo(TenantCustomRequestCondition other, HttpServletRequest request) {
    Double thisPriority = this.tenantCustomPointRepository.getPriority(TenantCustomContext.getTenantNum(), this.serviceName, this.customPointCode);
    Double otherPriority = this.tenantCustomPointRepository.getPriority(TenantCustomContext.getTenantNum(), this.serviceName, other.getCustomPointCode());
    LOGGER.debug("Tenant had authority to multi custom handler: tenantNum={}, this customPointCode={}, other customPointCode={}", new Object[] { TenantCustomContext.getTenantNum(), this.customPointCode, other.getCustomPointCode() });
    if (thisPriority != null && otherPriority == null)
      return -1; 
    if (thisPriority == null && otherPriority != null)
      return 1; 
    if (thisPriority != null)
      return (thisPriority.doubleValue() < otherPriority.doubleValue()) ? -1 : 1; 
    return 1;
  }
  
  public String getCustomPointCode() {
    return this.customPointCode;
  }
}
